<template>
  <div class="announcement-container">
    <div class="header">
      <div class="left">
        <h2>公告管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>发布公告
        </el-button>
      </div>
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索公告标题"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="announcements"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="important" label="重要" width="80">
          <template #default="{ row }">
            <el-tag :type="row.important ? 'danger' : 'info'">
              {{ row.important ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author.name" label="发布人" width="120" />
        <el-table-column prop="createTime" label="发布时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 公告表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
          />
        </el-form-item>
        <el-form-item label="重要公告" prop="important">
          <el-switch v-model="form.important" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AdminAnnouncementsPage'
}
</script>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAnnouncements, createAnnouncement, updateAnnouncement, deleteAnnouncement } from '@/api/admin/announcement'
import { formatDate } from '@/utils/format'

// 表格数据
const announcements = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索相关
const searchQuery = ref('')
const handleSearch = () => {
  currentPage.value = 1
  fetchAnnouncements()
}

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const submitting = ref(false)

const form = ref({
  title: '',
  content: '',
  important: false
})

const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ]
}

// 获取公告列表
const fetchAnnouncements = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      search: searchQuery.value || ''
    }
    console.log('Fetching announcements with params:', params)
    const response = await getAnnouncements(params)
    announcements.value = response.content
    total.value = response.totalElements
  } catch (error) {
    console.error('Failed to fetch announcements:', error)
    ElMessage.error(error.response?.data?.message || '获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 添加公告
const handleAdd = () => {
  dialogTitle.value = '发布公告'
  form.value = {
    title: '',
    content: '',
    important: false
  }
  dialogVisible.value = true
}

// 编辑公告
const handleEdit = (row) => {
  dialogTitle.value = '编辑公告'
  form.value = {
    id: row.id,
    title: row.title,
    content: row.content,
    important: row.important
  }
  dialogVisible.value = true
}

// 删除公告
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该公告吗？', '警告', {
      type: 'warning'
    })
    await deleteAnnouncement(row.id)
    ElMessage.success('删除成功')
    fetchAnnouncements()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete announcement:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const formData = {
      title: form.value.title.trim(),
      content: form.value.content.trim(),
      important: form.value.important || false
    }
    
    if (form.value.id) {
      await updateAnnouncement(form.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      await createAnnouncement(formData)
      ElMessage.success('发布成功')
    }
    
    dialogVisible.value = false
    fetchAnnouncements()
  } catch (error) {
    console.error('Form submission failed:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('提交失败，请检查表单内容')
    }
  } finally {
    submitting.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAnnouncements()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAnnouncements()
}

// 在组件挂载时获取公告列表
onMounted(() => {
  fetchAnnouncements()
})
</script>

<style scoped>
.announcement-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button-group) {
  .el-button {
    padding: 5px 12px;
  }
}
</style> 